package com.dragon.modules.yuegou.client.wechat.client.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sgy.ysq.core.web.SystemCode;
import com.sgy.ysq.wx.client.WxTokenClient;
import com.sgy.ysq.wx.model.WXTokenModel;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import tech.liuwu.commons.exception.BusinessException;

@Service
public class WxTokenClientImpl implements WxTokenClient {
    private  Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String getToken(String appId, String secret) {
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        //获取Token 所需参数
        String param = String.format("grant_type=client_credential&appid=%s&secret=%s", appId, secret);

        //http 请求头设置
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        //设置参数
        RequestEntity requestEntity = new StringRequestEntity(param);
        method.setRequestEntity(requestEntity);

        try {
            //执行请求
            client.executeMethod(method);

            //返回请求,判断状态
            if (method.getStatusCode() == HttpStatus.SC_OK) {//请求成功,状态200
                String response = method.getResponseBodyAsString();
                logger.debug("getToken Response:" + response);

                //转换成JSON,获取token 并返回
                JSONObject jsonObject = JSON.parseObject(response);
                String access_token = jsonObject.getString("access_token");
                if (StringUtils.isNotBlank(access_token)){
                    return access_token;
                }
                throw new BusinessException(SystemCode.TOKEN_ERROR);
            } else {//请求失败
                throw new Exception("http statusCode:" + String.valueOf(method.getStatusCode()) + "\n"
                        + method.getStatusText() + "\n" + "url:" + method.getURI());
            }
        } catch (Exception e) {
            logger.error(String.format("getToken 异常:%s", e.getMessage()), e);
            throw new BusinessException(SystemCode.TOKEN_ERROR);
        }
    }

    @Override
    public WXTokenModel getGZHToken(String code, String appid, String secret) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        //获取Token 所需参数
        String param = String.format("appid=%s&secret=%s&code=%s&grant_type=authorization_code", appid, secret,code);
        //http 请求头设置
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        //设置参数
        RequestEntity requestEntity = new StringRequestEntity(param);
        method.setRequestEntity(requestEntity);

        try {
            //执行请求
            client.executeMethod(method);

            //返回请求,判断状态
            if (method.getStatusCode() == HttpStatus.SC_OK) {//请求成功,状态200
                String response = method.getResponseBodyAsString();
                logger.debug("getToken Response:" + response);

                WXTokenModel wxTokenModel = new WXTokenModel();
                //转换成JSON,获取token 并返回
                JSONObject jsonObject = JSON.parseObject(response);
                String access_token = jsonObject.getString("access_token");
                String expires_in = jsonObject.getString("expires_in");
                String refresh_token = jsonObject.getString("refresh_token");
                String openid = jsonObject.getString("openid");
                String scope = jsonObject.getString("scope");
                String unionid = jsonObject.getString("unionid");
                if (StringUtils.isNotBlank(access_token)){
                    wxTokenModel.setAccessToken(access_token);
                    wxTokenModel.setExpiresIn(expires_in);
                    wxTokenModel.setRefreshToken(refresh_token);
                    wxTokenModel.setOpenid(openid);
                    wxTokenModel.setScope(scope);
                    wxTokenModel.setUnionId(unionid);
                    return wxTokenModel;
                }
                throw new BusinessException(SystemCode.TOKEN_ERROR);
            } else {//请求失败
                throw new Exception("http statusCode:" + String.valueOf(method.getStatusCode()) + "\n"
                        + method.getStatusText() + "\n" + "url:" + method.getURI());
            }
        } catch (Exception e) {
            logger.error(String.format("getToken 异常:%s", e.getMessage()), e);
            throw new BusinessException(SystemCode.TOKEN_ERROR);
        }
    }
}
